<?php

namespace app\admin\controller;

use app\admin\model\Admin as adminModel;
use app\LdapBase;
use app\admin\controller\Permissions;
use think\Config;
use \think\Db;

class Ldapgroup extends Permissions {

    public function groupList() {
        $ldap = new LdapBase();
        $groupList = $ldap->groupList();

        $this->assign('groupList', $groupList);

        return $this->fetch();
    }

    public function groupUsers() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        $userList = array();
        if (!empty($id)) {
            $ldap = new LdapBase();
            $groupInfo = $ldap->findGroup($id);
            if (!empty($groupInfo['memberuid']) && $groupInfo['memberuid']['count'] > 0) {
                for ($j = 0; $j < $groupInfo['memberuid']['count']; $j++) {
                    $uid = $groupInfo['memberuid'][$j];
                    $userInfo = $ldap->find($uid);
                    if (isset($userInfo['uid'])) {
                        $userList[] = $userInfo;
                    }
                }
            }
        }
        $this->assign('userList', $userList);
        return $this->fetch();
    }

    public function delete() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        if (!empty($id)) {
            $ldap = new LdapBase();
            $ret = $ldap->deleteGroup($id);
            if (!$ret) {
                return $this->error('删除群组信息失败');
            } else {
                //删除本地组
                //查询本地群组
                $cateInfo = Db::name('admin_cate')->where('name', $id)->find();
                if (!empty($cateInfo)) {
                    //删除组
                    Db::name('admin_cate')->where('id', $cateInfo['id'])->delete();
                    //删除组下人员
                    Db::name('admin_cate_relation')->where('cate_id', $cateInfo['id'])->delete();
                }


                return $this->success('删除群组信息成功', 'admin/ldapgroup/groupList');
            }
        }
        return $this->error('删除失败，请传正确的参数！');
    }

    public function publish() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        $ldap = new LdapBase();
        $groupList = $ldap->groupList();
        $this->assign('groupList', $groupList);

        if (!empty($id)) {
            //是修改操作提交
            if ($this->request->isPost()) {
                $post = $this->request->post();

                //验证群组是否存在                
                $groupInfo = $ldap->findGroup($post['id']);
                if (empty($groupInfo)) {
                    return $this->error('提交失败：该群组不存在');
                }

                $groupArr['cn'] = $post['id'];
                $groupArr['description'] = isset($post['description']) && !empty($post['description']) ? $post['description'] : " ";
                $groupArr['objectClass'][0] = "groupOfUniqueNames";
                $groupArr['objectClass'][1] = "top";

                $res = $ldap->editGroup($groupArr,$post['group_name']);
                if (!$res) {
                    return $this->error('修改群组信息失败');
                } else {
                    $selectUserArr = array();
                    if (!empty($post['selectUserArr'])) {
                        $selectUserArr = explode(',', $post['selectUserArr']);
                    }

                    $groupMember = array();
                    foreach ($groupList as $groupDetail) {
                        if ($post['id'] == $groupDetail['cn'] && is_array($groupDetail['memberuid'])) {
                            unset($groupDetail['memberuid']['count']);
                            $groupMember = $groupDetail['memberuid'];

                            foreach ($groupDetail['memberuid'] as $key2 => $uid2) {
                                //如果用户已经存在本次提交中，则不作处理
                                foreach ($selectUserArr as $key => $uid) {
                                    if ($uid == $uid2) {
                                        unset($selectUserArr[$key]);
                                        unset($groupMember[$key2]);
                                    }
                                }
                            }

                            foreach ($selectUserArr as $uid) {
                                $ret = $ldap->addToGroup($uid, $post['id']);
                            }

                            foreach ($groupMember as $user) {
                                $re = $ldap->delToGroup($user, $post['id']);
                            }

                            break;
                        }
                    }

                    //在本系统添加权限组
                    $groupModel = new \app\admin\model\AdminCate();
                    //验证角色组是否存在
                    $groupDetail = $groupModel->where('name', $post['id'])->find();
                    $groupId = 0;
                    if (empty($groupDetail)) {
                        $groupDetail['name'] = $post['id'];
                        $groupDetail['desc'] = isset($post['description']) && !empty($post['description']) ? $post['description'] : "";
                        $groupAddRst = $groupModel->allowField(true)->save($groupDetail);
                        $groupId = $groupModel->id;
                    }else if($groupDetail['name']!=$post['group_name']){
                        $groupName = $post['group_name'];
			$groupDesc = isset($post['description']) && !empty($post['description']) ? $post['description'] : "";
			$groupAddRst = $groupModel->where('id',$groupDetail['id'])->update(['name'=>$groupName,'desc'=>$groupDesc,'update_time'=>time()]);
			$groupId = $groupDetail['id'];
		    }else{
                        $groupId = $groupDetail['id'];
                    }
		    //删除原有群人员对应关系
		     foreach ($groupMember as $user) {
			$delUserModel = new adminModel();
			$delUserInfo = $delUserModel->where('name',$user)->find();
			
			$oldAdminCateModel = new \app\admin\model\AdminCateRelation();  
                    	$oldAdminCateModel->where('cate_id='.$groupId.' and admin_id='.$delUserInfo['id'])->delete();			
                      }
			
                    //增加添加用户到群的操作
                    if (!empty($selectUserArr)) {
                        foreach ($selectUserArr as $uid) {
                            //添加用户到ldap组
                            //添加用户到本地权限组
                            $userModel = new adminModel();
                            $userInfo = $userModel->where('name', $uid)->find();
                            if (!empty($userInfo)) {
                                $userId = $userInfo['id'];
                                $adminCateModel = new \app\admin\model\AdminCateRelation();                               
                                
                                $adminCateInfo = $adminCateModel->where('admin_id=' . $userId . ' and cate_id=' . $groupId)->find();
                                if (empty($adminCateInfo)) {
                                    $adminCateInfoNew = array();
                                    $adminCateInfoNew['admin_id'] = $userId;
                                    $adminCateInfoNew['admin_name'] = $userInfo['nickname'];
                                    $adminCateInfoNew['cate_id'] = $groupId;
                                    $adminCateInfoNew['cate_status'] = 1;
                                    $adminCateModel->allowField(true)->save($adminCateInfoNew);
                                }
                            }
                        }
                    }
                    return $this->success('修改群组信息成功', 'admin/ldapgroup/groupList');
                }
            } else {
                //查看详情
                $groupInfo = $ldap->findGroup($id);
                $groupInfo['memberuidstr'] = empty($groupInfo['memberuid']) ? array() : implode(',', $groupInfo['memberuid']);

                $userList = $ldap->userList();

                $this->assign('groupInfo', $groupInfo);
                $this->assign('userList', $userList);
                $this->assign('title', '编辑群组');
                return $this->fetch();
            }
        } else {
            //是新增操作 提交
            if ($this->request->isPost()) {

                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['group_name', 'require', '群组名称为必填字段'],
                    ['selectUserArr', 'require', '必须勾选组员'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证群组是否存在                
                $groupInfo = $ldap->findGroup($post['group_name']);
                if (!empty($groupInfo) && isset($groupInfo['count']) && $groupInfo['count'] > 0) {
                    return $this->error('提交失败：该群组已存在');
                }

                $groupArr['cn'] = $post['group_name'];
                $groupArr['description'] = isset($post['description']) && !empty($post['description']) ? $post['description'] : " ";
                $groupArr['objectClass'][0] = "groupOfUniqueNames";
                $groupArr['objectClass'][1] = "top";
                $selectUserArr = explode(',', $post['selectUserArr']);
                foreach ($selectUserArr as $uid) {
                    $ldapConf = Config::get("ldap");
                    $udn = 'uid=' . $uid . ',ou=' . $ldapConf['personOu'] . ',' . $ldapConf['baseDn'];
                    $groupArr['uniqueMember'][] = $udn;
                }

                $res = $ldap->addGroup($groupArr);
                if (!$res) {
                    return $this->error('添加群组信息失败');
                } else {
                    //在本系统添加权限组
                    $groupModel = new \app\admin\model\AdminCate();
                    //验证角色组是否存在
                    $groupDetail = $groupModel->where('name', $post['group_name'])->find();
                    $groupId = 0;
                    if (empty($groupDetail)) {
                        $groupDetail['name'] = $post['group_name'];
                        $groupDetail['desc'] = isset($post['description']) && !empty($post['description']) ? $post['description'] : "";
                        $groupAddRst = $groupModel->allowField(true)->save($groupDetail);
                        $groupId = $groupModel->id;
                    } else {
                        $groupId = $groupDetail['id'];
                    }

                    //增加添加用户到群的操作
                    if (!empty($post['selectUserArr'])) {
                        $selectUserArr = explode(',', $post['selectUserArr']);
                        $userModel = new adminModel();
                        foreach ($selectUserArr as $uid) {
                            //添加用户到本地权限组
                            $userInfo = $userModel->where('name', $uid)->find();
                            if (!empty($userInfo)) {
                                $userId = $userInfo['id'];
                                $adminCateModel = new \app\admin\model\AdminCateRelation();
                                $adminCateInfo = $adminCateModel->where('admin_id=' . $userId . ' and cate_id=' . $groupId)->find();
                                if (empty($adminCateInfo)) {
                                    $adminCateInfoNew = array();
                                    $adminCateInfoNew['admin_id'] = $userId;
                                    $adminCateInfoNew['admin_name'] = $userInfo['name'];
                                    $adminCateInfoNew['cate_id'] = $groupId;
                                    $adminCateInfoNew['cate_status'] = 1;
                                    $adminCateModel->allowField(true)->save($adminCateInfoNew);
                                }
                            }
                        }
                    }


                    return $this->success('添加群组信息成功', 'admin/ldapgroup/groupList');
                }
            } else {
                //非提交操作  新增空白页
                $ldap = new LdapBase();
                $userList = $ldap->userList();

                $this->assign('userList', $userList);
                return $this->fetch();
            }
        }
    }

}
